<?php
namespace app\model;

class ChatSession extends BaseModel
{
    protected $name = 'chat_sessions';

    // 自动时间戳
    protected $autoWriteTimestamp = true;

    // 类型转换
    protected $type = [
        'ai_analyzed_at' => 'integer',
        'started_at' => 'integer',
        'last_message_at' => 'integer',
        'created_at' => 'integer',
        'updated_at' => 'integer',
        'delete_time' => 'integer'
    ];

    // 会话类型常量
    const TYPE_NORMAL = 1;    // 普通会话
    const TYPE_PROJECT = 2;   // 项目会话
    const TYPE_REMINDER = 3;  // 提醒会话
    const TYPE_LEARNING = 4;  // 学习会话

    /**
     * 关联用户
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 关联项目
     */
    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    /**
     * 关联提醒
     */
    public function reminder()
    {
        return $this->belongsTo(Reminder::class);
    }

    /**
     * 关联学习记录
     */
    public function learningRecord()
    {
        return $this->belongsTo(LearningRecord::class, 'learning_records_id');
    }

    /**
     * 关联消息
     */
    public function messages()
    {
        return $this->hasMany(ChatMessage::class, 'session_id');
    }

    /**
     * 获取关键词数组
     */
    public function getKeywordsArray()
    {
        return $this->keywords ? explode(',', $this->keywords) : [];
    }

    /**
     * 设置关键词
     */
    public function setKeywords(array $keywords)
    {
        $this->keywords = implode(',', array_unique(array_filter($keywords)));
    }

    /**
     * 更新最后消息时间
     */
    public function updateLastMessageTime()
    {
        $this->last_message_at = time();
        $this->save();
    }
} 